package com.fleafinder.xmlparser;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

import com.fleafinder.CommonConstants;
import com.fleafinder.entity.MarketType;

public class MarketTypeXmlParser {
	
	public static final String TAG_MARKEDTYPES = "markedtypes";
	public static final String TAG_MARKEDTYPE = "markedtype";
	public static final String TAG_ID = "id";
	public static final String TAG_NAME = "name";
	
	public static final int I_TAG_MARKEDTYPES = 0;
	public static final int I_TAG_MARKEDTYPE = 1;
	public static final int I_TAG_ID = 2;
	public static final int I_TAG_NAME = 3;
	
	private List<MarketType> marketTypeList = null;
	
	private int currentTag = -1;
	
	public MarketTypeXmlParser(){
		this.marketTypeList = new ArrayList<MarketType>();
	}
	
	public List<MarketType> getMarketTypeList(){
		return marketTypeList;
	}
	
	/**
	 * @param in
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public void parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in, CommonConstants.ENCODING_UTF_8);
            
            int tag = parser.next();
            MarketType m = null;
            while(tag != XmlPullParser.END_DOCUMENT){
            	if(tag == XmlPullParser.START_TAG){
            		if(TAG_MARKEDTYPE.equals(parser.getName())){
    					currentTag = I_TAG_MARKEDTYPE;
    					m = new MarketType();
    					
    					readMarketTypeEntry(parser, m);
    					this.marketTypeList.add(m);
    				}
            	}
            	tag = parser.next();            	
            }
            
        } catch(Exception e){
        	e.printStackTrace();
        } finally {
            in.close();
        }
    }

	
	/**
	 * @param parser
	 * @param m
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	public MarketType readMarketTypeEntry(XmlPullParser parser, MarketType m) throws XmlPullParserException, IOException{
			
		while(true){
			int next = parser.getEventType();
			
			if(next == XmlPullParser.END_TAG){
				if(currentTag == I_TAG_MARKEDTYPE){
					break;
				} else {
					currentTag = I_TAG_MARKEDTYPE;
					//continue;
				}
			} else if(next == XmlPullParser.START_TAG){
				if(TAG_ID.equals(parser.getName())){
					currentTag = I_TAG_ID;
				} else if(TAG_NAME.equals(parser.getName())){
					currentTag = I_TAG_NAME;
				}
			} else if(next == XmlPullParser.TEXT){
				if(currentTag == I_TAG_ID){
					m.setMarketId(Integer.parseInt(parser.getText()));
				} else if(currentTag == I_TAG_NAME){
					m.setMarketTypeName(parser.getText());
				}
			}
			
			parser.next();
		}
		return m;
	}
}
